/**
 * 堆叠南丁格尔玫瑰图
 */
import BaseChart from '../../BaseChart.js'
export default class RosePie extends BaseChart {
	constructor(id, data) {
		super(id, data)

		this.color = d3.quantize((t) => d3.interpolateSpectral(t * 0.8 + 0.1), this.data.length)

		this.stackKeys = null
		this.nameKey = null
	}

	setNameKey(k) {
		this.nameKey = k
		return this
	}

	setStackKeys(k) {
		this.stackKeys = k
		return this
	}

	setInnerRadius(r) {
		this.innerRadius = r
		return this
	}

	init() {
		// 继承父类
		this.initSvg()
		this.initMainGroup()
		this.initArcsGroup()
		this.initZoom()
		return this
	}

	initArcsGroup() {
		this.arcsGroup = this.mg.append('g')
	}

	initZoom() {
		this.svg.call(d3.zoom().on('zoom', this.zoomed))
	}

	/**
	 * 更新视图部分
	 */
	render(data) {
		if (data) {
			this.data = data
		}
		this.renderPie()
		this.renderScale()
		this.renderStackData()
		this.renderPieGroup()
		this.renderPieArc()
		return this
	}

	/**
	 * pie布局算法
	 * 返回一个新对象，包含pie的角度
	 */
	renderPie() {
		this.pie = d3.pie().value((d) => {
			return d3.sum(Object.values(d))
		})
	}

	/**
	 * 数据比例尺
	 */
	renderScale() {
		let dataSum = []
		this.data.forEach((d) => {
			let val = 0
			this.stackKeys.forEach((key) => {
				val += +d[key]
			})
			dataSum.push(val)
		})
		let radius = Math.min(this.innerHeight, this.innerWidth)
		// this.r = d3.scaleLog()
		//   .domain([25, d3.max(dataSum)])
		//   .range([10, radius / 2])
		this.r = d3
			.scaleLinear()
			.domain([0, d3.max(dataSum)])
			.range([this.innerRadius, radius / 2])
	}

	/**
	 * 生成堆叠数据的算法
	 */
	renderStackData() {
		this.stackData = d3
			.stack()
			.keys(this.stackKeys)
			.order(d3.stackOrderNone)
			.offset(d3.stackOffsetNone)
			.value((d, key) => d.data[key])(this.pie(this.data))
	}

	/**
	 * 绘制每一层的饼图的容器
	 */
	renderPieGroup() {
		this.pieGroup = this.arcsGroup
			.selectAll('g')
			.data(this.stackData)
			.join('g')
			.attr('fill', (d, i) => this.color[i % 10])
			.attr('transform', 'translate(' + this.innerWidth / 2 + ',' + this.innerHeight / 2 + ')') //圆心位置
	}
	/**
	 * 针对每一层进行扇形的绘制
	 */
	renderPieArc() {
		this.arcs = this.pieGroup
			.selectAll('path')
			.data((d) => d)
			.join('path')
			.transition()
			.attr('d', (d) => this.getArcRose(d))
			.attr('stroke', (d, i) => this.color[i % 10])
	}

	/**
	 * arc弧线布局算法
	 * 返回的是path的d属性，字符串
	 */
	getArcRose(data) {
		let innerRadius = this.r(data[0]) //内半径
		let outerRadius = this.r(data[1]) //外半径
		//！！！对数比例尺，不能为0
		if (!innerRadius) {
			innerRadius = 0.01
		}
		return d3.arc()({
			innerRadius: innerRadius,
			outerRadius: outerRadius,
			startAngle: data.data.startAngle,
			endAngle: data.data.endAngle,
		})
	}

	// 伸缩函数
	zoomed = (event) => {
		this.mg.attr(
			'transform',
			`translate(${event.transform.x},${event.transform.y}) scale(${event.transform.k})`
		)
	}
}
